#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from google.appengine.dist import use_library
use_library('django', '1.2')

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util, template

import logging

import models
import dojo_rest

class MainHandler(webapp.RequestHandler):
    def get(self):
        template_values = {
            'greetings': 'Hello',
        }

        path = os.path.join(os.path.dirname(__file__), 'templates/index.template')
        self.response.out.write(template.render(path, template_values))

class RestInterceptor(webapp.RequestHandler):
    # add all models from some other module, and/or...
    dojo_rest.Dispatcher.add_models_from_module(models)       

    # configure the rest dispatcher to know what prefix to expect on request urls
    dojo_rest.Dispatcher.base_url = "/rest"
    
    def __init__(self):
        super(RestInterceptor, self).__init__()
        logging.info("RestInterceptor instantiated.")
        self.restDispatcher = dojo_rest.Dispatcher() 
                       
    def initialize(self, request, response):        
        super(RestInterceptor, self).initialize(request, response)
        logging.info("RestInterceptor initialized.")
        request.disp_query_params_ = None
        response.disp_cache_resp_ = True
        response.disp_out_type_ = "application/json"
        self.restDispatcher.initialize(request, response)
    
    def get(self, *_):        
        logging.info("Intercepted GET")
        self.restDispatcher.get()
        
    def post(self, *_):
        logging.info("Intercepted POST")
        self.restDispatcher.post()
    
    def put(self, *_):
        logging.info("Intercepted PUT")
        self.restDispatcher.post()
        
    def delete(self, *_):
        logging.info("Intercepted DELETE")
        self.restDispatcher.delete()
        
def main():
   
    # create console handler and set level to debug
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    
    # create formatter
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    
    # add formatter to ch
    ch.setFormatter(formatter)
    
    # add ch to logger
    logger = logging.getLogger("rest")
    logger.setLevel(logging.DEBUG)
    logger.addHandler(ch)

    application = webapp.WSGIApplication(
        [
            ('/', MainHandler),
            ('/rest/.*', RestInterceptor)            
        ],
        debug=True)
    util.run_wsgi_app(application)
    
if __name__ == '__main__':    
    main()




